package serivce

import (
	"golang.org/x/crypto/bcrypt"
	"guard/internal/app/user/models"
	"guard/internal/errors"
	"guard/internal/tool"
)

/**
用户管理
*/

func (s *userServiceImpl) UserPage(current, size int) (*tool.Paginator, error) {
	paginator := s.st.SelUserPage(current, size)
	if paginator == nil {
		return nil, errors.OtherError("分页异常")
	}
	// 创建新的dto返回给前端
	var udtList []*models.UserDto
	userL := paginator.Data.([]models.User)
	for _, v := range userL {
		dto := models.NewUserDto(&v)
		udtList = append(udtList, dto)
	}
	paginator.Data = udtList
	return paginator, nil
}

func (s *userServiceImpl) QueryUser(condition string) (ud []*models.UserDto, err error) {
	user, err := s.st.SelUserQuery(0, condition)
	if err != nil {
		return nil, errors.OtherError("记录不存在")
	}
	// 如果没有数据，就返回空
	if user.Username == "" || len(user.Username) == 0 {
		return nil, nil
	}
	dto := models.NewUserDto(user)
	ud = append(ud, dto)
	return ud, nil
}

func (s *userServiceImpl) AddUser(user *models.User) error {
	// 密码被隐藏，所以需要查询得到密码
	queryUser, _ := s.st.SelUserQuery(user.Id, user.Username)

	// 如果查询到了就是创建
	if queryUser.Username == "" || len(queryUser.Username) == 0 {
		// 加密
		generateFromPassword, _ := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
		user.Password = string(generateFromPassword)
	} else {
		user.Password = queryUser.Password
	}
	// 保存
	err := s.st.SaveOrUpdateUser(*user)
	if err != nil {
		return errors.OtherError("保存失败")
	}
	return nil
}

func (s *userServiceImpl) RemoveUser(username string) error {
	err := s.st.DeleteUser(username)
	if err != nil {
		return errors.OtherError("删除失败")
	}
	return nil
}
